package com.business_clean.ui.activity.main;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.service.LocService;
import com.business_clean.app.service.MarkUploadService;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.appupdate.AppCheckUpdateUtil;
import com.business_clean.app.weight.camera.CaptureButton;
import com.business_clean.app.weight.camera.CaptureListener;
import com.business_clean.data.mode.init.InitDataEntity;
import com.business_clean.data.mode.login.UserInfo;
import com.business_clean.data.mode.todo.TodoList;
import com.business_clean.databinding.ActivityMainBinding;
import com.business_clean.ui.activity.camera.WatermarkCameraActivity;
import com.business_clean.ui.adapter.viewpager2.FragmentLazyStateAdapter;
import com.business_clean.ui.fragment.main.CameraFragment;
import com.business_clean.ui.fragment.main.RosterFragment;
import com.business_clean.ui.fragment.main.TodoFragment;
import com.business_clean.ui.fragment.main.WorkbenchFragment;
import com.business_clean.ui.fragment.main.WorkingCircleFragment;
import com.business_clean.viewmodel.request.MainViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chaychan.library.BottomBarItem;
import com.chaychan.library.BottomBarLayout;
import com.chaychan.library.TabData;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;
import me.hgj.mvvmhelper.net.manager.NetState;

public class MainActivity extends BaseActivity<MainViewModel, ActivityMainBinding> {

    private int[] mIconUnselectIds = {
            R.mipmap.icon_home_workbench_unselected, R.mipmap.icon_home_todo_unselected,
            R.mipmap.icon_home_camera_unselected, R.mipmap.icon_home_circle_unselected, R.mipmap.icon_home_roster_unselected};

    private int[] mIconSelectIds = {
            R.mipmap.icon_home_workbench_selected, R.mipmap.icon_home_todo_selected,
            R.mipmap.icon_home_camera_unselected, R.mipmap.icon_home_circle_selected, R.mipmap.icon_home_roster_selected};


    private static final long TIME_INTERVAL = 2000; // 两次点击间的最大时间间隔
    private long backPressedTime;


    private LocService locService;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        //从本地拿用户的数据
        initUserConfig();

        ArrayList<Fragment> mFragments = new ArrayList<>();
        //在这里做权限的处理
        mFragments.add(new WorkbenchFragment());
        mFragments.add(new TodoFragment());
        mFragments.add(new CameraFragment());
        mFragments.add(new WorkingCircleFragment());
        mFragments.add(new RosterFragment());


        mDatabind.viewPager2.setUserInputEnabled(false);
        mDatabind.viewPager2.setOffscreenPageLimit(mFragments.size());
        mDatabind.viewPager2.setAdapter(new FragmentLazyStateAdapter(this, mFragments));

        List<TabData> tabData = new ArrayList<>();
        tabData.add(new TabData("首页", R.mipmap.icon_home_workbench_unselected, R.mipmap.icon_home_workbench_selected));
        tabData.add(new TabData("待办", R.mipmap.icon_home_todo_unselected, R.mipmap.icon_home_todo_selected));
//        tabData.add(new TabData("拍照", R.mipmap.icon_home_camera_unselected, R.mipmap.icon_home_camera_unselected));
        tabData.add(new TabData("工作群", R.mipmap.icon_home_circle_unselected, R.mipmap.icon_home_circle_selected));
        tabData.add(new TabData("花名册", R.mipmap.icon_home_roster_unselected, R.mipmap.icon_home_roster_selected));
        mDatabind.bottomLayout.setData(tabData);
        mDatabind.bottomLayout.setViewPager2(mDatabind.viewPager2);

        mViewModel.requestTodoList(1, 1);//产品要求，每次点击下方底部 bar 的时候去请求待办的接口，更新未读消息

        //判断下是否开启定位权限
        if (XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
            getCurrentLocation();
        }
        //请求源数据
        mViewModel.requestInitData();
        //检查是否需要更新
        AppCheckUpdateUtil.checkVersionNew(false);

        //如果领班跟保洁员 直接进去拍照界面
        if (Constant.ROLE_LEADER || Constant.ROLE_CLEANER) {
            XXPermissions.with(MainActivity.this).permission(
                            Permission.CAMERA,
                            Permission.ACCESS_FINE_LOCATION,
                            Permission.MANAGE_EXTERNAL_STORAGE,
                            Permission.RECORD_AUDIO)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            if (allGranted) {
                                startActivity(new Intent(MainActivity.this, WatermarkCameraActivity.class));
                                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                            }
                        }
                    });
        }

    }

    /**
     * 从本地取值 设置默认值
     */
    private void initUserConfig() {
        String userInfoJson = MMKVHelper.getString(ConstantMMVK.USER_INFO);
        if (!TextUtils.isEmpty(userInfoJson)) {
            UserInfo userInfo = new Gson().fromJson(userInfoJson, UserInfo.class);
            CommonUtils.updateLocalUserData(userInfo);
        }
    }

    /**
     * 获取当前定位
     */
    private void getCurrentLocation() {
//        locService = new LocService(this);
//        locService.registerListener(mListener);
//        locService.setLocationOption(locService.getDefaultLocationClientOption());
//        locService.start();
    }


    @Override
    public void initObserver() {
        App.appViewModelInstance.getUserInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(UserInfo userInfo) {
                CommonUtils.updateLocalUserData(userInfo);
            }
        });

        App.appViewModelInstance.getBackPosition().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer position) {
                mDatabind.bottomLayout.setCurrentItem(position);
            }
        });

        //添加员工的监听  也需要去刷新角标
        App.appViewModelInstance.getRefreshTodoTotal().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {//更新未读消息
                mDatabind.bottomLayout.setUnread(1, integer);
            }
        });
        App.appViewModelInstance.getRefreshTodo().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                mViewModel.requestTodoList(1, 1);
            }
        });

        App.appViewModelInstance.getRefreshMember().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                mViewModel.requestTodoList(1, 1);
            }
        });
    }


    @Override
    public void onBindViewClick() {
        //item拦截 后期如果开启了收费模块，可以做处理
        mDatabind.bottomLayout.setOnPageChangeInterceptor(new BottomBarLayout.OnPageChangeInterceptor() {
            @Override
            public boolean onIntercepted(int position) {
                if (position == 2) {//如果是拍照的话，先请求权限
                    XXPermissions.with(MainActivity.this).permission(Permission.CAMERA, Permission.ACCESS_FINE_LOCATION,
                                    Permission.MANAGE_EXTERNAL_STORAGE, Permission.RECORD_AUDIO)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                    if (allGranted) {
                                        Intent intent = new Intent(MainActivity.this, WatermarkCameraActivity.class);
                                        ActivityOptionsCompat compat = ActivityOptionsCompat.makeScaleUpAnimation(mDatabind.bottomLayout,
                                                mDatabind.bottomLayout.getWidth() / 2, mDatabind.bottomLayout.getHeight() / 2, 0, 0);

                                        startActivity(intent, compat.toBundle());
//                                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                                    }
                                }
                            });
                    return true;
                }
                return false;
            }
        });

        //item 选中监听
        mDatabind.bottomLayout.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            @Override
            public void onItemSelected(BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
                //previousPosition 是上一个的下标，currentPosition 是现在下标
                LogExtKt.logE("previousPosition - " + previousPosition + " ; currentPosition - " + currentPosition, "");
                mViewModel.requestTodoList(1, 1);//产品要求，每次点击下方底部 bar 的时候去请求待办的接口，更新未读消息
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        //源数据接口，把内容都存储起来
        mViewModel.getInitData().observe(this, new Observer<InitDataEntity>() {
            @Override
            public void onChanged(InitDataEntity initDataEntity) {
                MMKVHelper.putString(ConstantMMVK.INIT_DATA, JSON.toJSONString(initDataEntity));
                MMKVHelper.putString(ConstantMMVK.IN_CLASS_TIME_LIST, JSON.toJSONString(initDataEntity.getIn_class_time_list()));
                MMKVHelper.putString(ConstantMMVK.OUT_CLASS_TIME_LIST, JSON.toJSONString(initDataEntity.getOut_class_time_list()));
            }
        });

        //设置角标
        mViewModel.getTodoList().observe(this, new Observer<TodoList>() {
            @Override
            public void onChanged(TodoList todoList) {
                if (!Constant.ROLE_LEADER || !Constant.ROLE_CLEANER) {
                    int number = Integer.valueOf(todoList.getTotal());
                    App.appViewModelInstance.getRefreshTodoTotal().setValue(number);
                }
            }
        });
    }

    /**
     * 百度的定位回调
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        /**
         * 定位请求回调函数
         * @param location 定位结果
         */
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtils.e("获取地址定位--" + location.getAddrStr());
                locService.stop();
                Constant.LATITUDE = location.getLatitude();
                Constant.LONGITUDE = location.getLongitude();
                Constant.ADDRESS = location.getAddrStr();
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
            LogUtils.e("获取地址定位onConnectHotSpotMessage--" + s + " ; code =" + i);
        }

        /**
         * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
         * @param locType 当前定位类型
         * @param diagnosticType 诊断类型（1~9）
         * @param diagnosticMessage 具体的诊断信息释义
         */
        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
            LogUtils.e("获取地址定位onLocDiagnosticMessage--" + diagnosticMessage + " ; code =" + diagnosticType + "  定位类型 ->" + locType);
        }
    };


    @Override
    protected void onStop() {
        if (locService != null) {
            locService.unregisterListener(mListener); //注销掉监听
            locService.stop();
        }
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locService) {
            locService.unregisterListener(mListener); //注销掉监听
            locService.disableAssistantLocation();
            locService.stop();
        }
        //停止服务
        ServiceUtils.stopService(MarkUploadService.class);
    }

    @Override
    public void onBackPressed() {
        if (backPressedTime + TIME_INTERVAL > System.currentTimeMillis()) {
            super.onBackPressed();
            AppExtKt.finishAllActivity();
            System.exit(0);
        } else {
            Toast.makeText(this, "再次点击返回按钮退出应用", Toast.LENGTH_SHORT).show();
        }

        backPressedTime = System.currentTimeMillis();
    }

    @Override
    public void onNetworkStateChanged(@NonNull NetState netState) {
        super.onNetworkStateChanged(netState);
        if (netState.isSuccess()) {
            ToastUtil.show("有网络了");
        } else {
            ToastUtil.show("断网了，请检查网络");
        }
    }
}